package com.fit.spring.boot.mapper.autoconfigure;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

/**
 * mapper配置文件
 * @author hcl
 *
	 以下是配置文件中可配置的属性列表：
			mappers
			UUID
			IDENTITY
			seqFormat
			catalog
			schema
			ORDER
			notEmpty//TRUE
			enableMethodAnnotation//TRUE
			checkExampleEntityClass//TRUE
			useSimpleType//TRUE
			//注册新的基本类型，以逗号隔开，使用全限定类名
			simpleTypes
			style
			
	PS:由于此配置读取叫快,所以不能配置在application.properties文件中

 */
public class MapperProperties {

	/**
	 * 前缀
	 */
	private final static String MAPPER_PREFIX = "mybatis.mapper";
	
	private Properties properties;
	
	@SuppressWarnings("unchecked")
	public MapperProperties(Environment environment){
		properties = new Properties();
		if(environment instanceof ConfigurableEnvironment){
			ConfigurableEnvironment ev = (ConfigurableEnvironment)environment;
			MutablePropertySources mps = ev.getPropertySources();
			Iterator<PropertySource<?>> it = mps.iterator();
			while(it.hasNext()){
				PropertySource<?> ps = it.next();
				Object source = ps.getSource();
				Iterator<Entry<Object, Object>> sourceIt = null;
				if(source instanceof Properties){
					sourceIt = ((Properties)source).entrySet().iterator();
				}else if(source instanceof HashMap){
					sourceIt = ((HashMap<Object, Object>)source).entrySet().iterator();
				}
				if(sourceIt != null){
					while(sourceIt.hasNext()){
						Entry<Object, Object> entry = sourceIt.next();
						String key = entry.getKey().toString();
						if(key.startsWith(MAPPER_PREFIX+".")){
							key = key.substring(MAPPER_PREFIX.length()+1);
							String value = entry.getValue().toString();
							properties.put(key, value);
						}
					}
				}
			}
		}
	}
	
	
	/**
	 * 获取配置文件
	 * @return
	 */
	public Properties getProperties(){
		return properties;
	}
}
